<template>
  <div class="constellation-container">
    <!-- 导航 -->
    <van-nav-bar>
      <template #left>
        <span @click="$router.back()">
        <svg-icon style="margin-right: 3px;" icon-class='fanhui' width="23px" height="23px" class="icon"/>
        </span>
        返回
      </template>
      <template #right>
        星座运势
      </template>
    </van-nav-bar>
    <div class="todayDay">
      <!-- 时间选择-->
      <DatePicker v-model="selectedDate" :masks="masks" @input="handleSelected" title-position="left" color="pink">
        <template v-slot="{ inputValue, inputEvents }">
          <input
            class="selectedTime"
            :value="inputValue"
            v-on="inputEvents"/>
        </template>
      </DatePicker>
    </div>

    <div class="whiteWrap">
      <div class="luckWrap">
        <div class="luckLeft">
          <van-image
            round
            width="100px"
            height="100px"
            fit="cover"
            :src="startValue?require(`@/assets/constellation/${startValue}.png`) : require(`@/assets/constellation/${getZodiacSign(userInfo.birthday).name}.png`)"
          />
          <van-popover v-model="showPopover" trigger="click" @select="onSelect" :actions="actions">
            <template #reference>
              <van-button type="default" icon-position="right">
                {{ startValue ? startValue : getZodiacSign(userInfo.birthday).name }}
                <template #icon>
                  <svg-icon icon-class='downSelect' width="18px" height="18px" class="icon"/>
                </template>
              </van-button>
            </template>
          </van-popover>
          <div class="time">{{ getZodiacSign(userInfo.birthday).time }}</div>
        </div>
        <div class="luckRight">
          <p style="margin-top: 0">工作指数：
            <van-rate v-model="workValue" void-color="#ccc" color="#9e9fe5" allow-half readonly/>
          </p>
          <p>健康指数：
            <van-rate v-model="healthyValue" void-color="#ccc" color="#83b9f5" allow-half readonly/>
          </p>
          <p>爱情指数：
            <van-rate v-model="loveValue" void-color="#ccc" color="#eb93b7" allow-half readonly/>
          </p>
          <p>财运指数：
            <van-rate v-model="moneyValue" void-color="#ccc" color="#f7d979" allow-half readonly/>
          </p>
          <p>幸运颜色：{{ colorValue }}</p>
          <p>幸运数字：{{ numValue }}</p>
        </div>
      </div>
      <van-divider :style="{ color: '#ec87c0', borderColor: '#ec87c0', padding: '0 16px' }">综合运势</van-divider>
      <div class="circle-progress">
        <div class="progress-text"></div>
        <div class="num">{{ this.renderList[0].content }}</div>
        <canvas class="progress-canvas" width="200" height="200"></canvas>
      </div>
      <div class="sum">综合指数</div>
      <div class="desc">{{ this.renderList[8].content }}</div>
    </div>
    <div class="doubleWrap">
      <van-popover
        v-model="person1Show"
        trigger="click"
        @select="onPerson1"
        :actions="actions"
        placement="top"
      >
        <template #reference>
          <van-button type="default" icon-position="right">
            {{ person1 }}
            <template #icon>
              <svg-icon icon-class='downSelect' width="18px" height="18px" class="icon"/>
            </template>
          </van-button>
        </template>
      </van-popover>
      <div class="matchBtn" @click="doubleMatch">
        <svg-icon icon-class='chukong' width="70px" height="70px" class="icon"/>
      </div>
      <van-popover
        v-model="person2Show"
        trigger="click"
        @select="onPerson2"
        :actions="actions"
        placement="top"
      >
        <template #reference>
          <van-button type="default" icon-position="right">
            {{ person2 }}
            <template #icon>
              <svg-icon icon-class='downSelect' width="18px" height="18px" class="icon"/>
            </template>
          </van-button>
        </template>
      </van-popover>
    </div>
    <van-dialog v-model="isMatchShow" title="匹配结果">
      <div class="grade" v-html="formatGrade"></div>
      <div class="content" v-html="formatContent"></div>
    </van-dialog>
  </div>
</template>

<script>

import dayjs from 'dayjs'
import { getUserInfoAPI } from '@/api'
import { getZodiacSign } from '@/utils/start'
import DatePicker from 'v-calendar/lib/components/date-picker.umd'

export default {
  name: 'constellationIndex',
  components: {
    DatePicker
  },
  data () {
    return {
      selectedDate: new Date(),
      masks: {
        input: 'WWW   M 月 D 日'
      },
      workValue: 2,
      healthyValue: 3,
      loveValue: 2.5,
      moneyValue: 3,
      colorValue: '',
      numValue: '',
      userInfo: {},
      loverInfo: {},
      startValue: '',
      startDate: '',
      person1: '白羊座',
      person2: '金牛座',
      showPopover: false,
      person1Show: false,
      person2Show: false,
      isMatchShow: false,
      formatContent: '',
      formatGrade: '',
      actions: [
        { text: '白羊座' },
        { text: '金牛座' },
        { text: '双子座' },
        { text: '巨蟹座' },
        { text: '狮子座' },
        { text: '处女座' },
        { text: '天秤座 ' },
        { text: '天蝎座' },
        { text: '射手座' },
        { text: '摩羯座' },
        { text: '水瓶座' },
        { text: '双鱼座' }
      ],
      renderList: [
        { type: '综合指数', content: '65%' },
        { type: '爱情指数', content: '80%' },
        { type: '工作指数', content: '65%' },
        { type: '财运指数', content: '60%' },
        { type: '健康指数', content: '70%' },
        { type: '幸运颜色', content: '橄榄绿' },
        { type: '幸运数字', content: '0' },
        { type: '贵人星座', content: '双子座' },
        {
          type: '今日概述',
          content: '今天水瓶座和另一半之间可能会发生一些冲突，吵架也会影响你工作的心情，建议调整好心态，两个人把问题解决，不要越拖越晚，冷战不是好的处理办法。'
        }
      ],
      MatchData: {
        title: '处女座：水瓶座',
        grade: '友情：★★ 爱情：★★ 婚姻：★★ 亲情：★★★',
        content: '怎样形容你们这一对？其实你们不会摆在一起！感情的开始通常是处女座觉得水瓶座这个朋友有意思，平易近人，见多识广，正是自己所欣赏的。而水瓶座也会因为贪新鲜觉得处女座的人很特别，和他以前有过的情人有不同之处，想试试在一起。可惜，水瓶座一旦深入处女的世界，会觉得有处女座的人什么事都要抓得很紧，死板固执，不晓得转弯没关系，还过份罗嗦，跟他根本沟通不了。而处女座也搞不清水瓶究竟想怎样，变化无常不说，还时常想一些不切实际的事，真有点怕了这家伙！　　在性方面有高配合度，但这不是你俩的生活重心，如果感情光靠性维持，很难长久相处下去的。　　希望你们可以有好长好长的缘份，打破宿命啦！'
      },
      progress: 0,
      canvas: null,
      ctx: null,
      x: 0,
      y: 0,
      radius: 0,
      startAngle: -Math.PI / 2,
      endAngle: 0,
      matchRate: 0
    }
  },
  created () {
    this.loadUserInfo()
  },
  updated () {
    this.getConstellation()
  },
  mounted () {
    this.canvas = this.$el.querySelector('.progress-canvas')
    this.ctx = this.canvas.getContext('2d')
    this.x = this.canvas.width / 2
    this.y = this.canvas.height / 2
    this.radius = this.canvas.width / 2 - 10
    this.drawCircleProgress()
    this.startAnimation()
  },
  computed: {
    attrs () {
      return [
        {
          key: 'today',
          highlight: {
            color: 'purple',
            fillMode: 'outline'
          },
          dates: new Date()
        }
      ]
    }
  },
  methods: {
    dayjs,
    getZodiacSign,
    // 请求用户信息
    async loadUserInfo () {
      try {
        const res = await getUserInfoAPI()
        console.log(res)
        if (res.data.message === 'jwt expired') {
          this.loginOutShow = true
          return
        }
        this.userInfo = res.data.data
        this.loverInfo = res.data.loverData
      } catch (error) {
        console.log(error)
      }
    },
    onSelect (action) {
      this.startValue = action.text
    },
    onPerson1 (action) {
      this.person1 = action.text
    },
    onPerson2 (action) {
      this.person2 = action.text
    },
    getConstellation () {
      fetch(`https://apis.tianapi.com/star/index?key=c11a19c8088cd1833a55587b1eb8bb87
      &astro=${this.startValue ? this.startValue : getZodiacSign(this.userInfo.birthday).name}
      &date=${this.startDate ? this.startDate : dayjs().format('YYYY-MM-DD')}`)
        .then(response => response.json())
        .then(data => {
          this.renderList = data.result.list
          this.workValue = this.convertNum(this.renderList[2].content)
          this.healthyValue = this.convertNum(this.renderList[4].content)
          this.loveValue = this.convertNum(this.renderList[1].content)
          this.moneyValue = this.convertNum(this.renderList[3].content)
          this.colorValue = this.renderList[5].content
          this.numValue = this.renderList[6].content
        })
        .catch(error => console.error(error))
    },
    convertNum (num) {
      return parseFloat((parseInt(num) / 100 * 5).toFixed(1))
    },
    doubleMatch () {
      fetch(`https://apis.tianapi.com/xingzuo/index?key=c11a19c8088cd1833a55587b1eb8bb87
      &me=${this.person1.substring(0, 2)}
      &he=${this.person2.substring(0, 2)}`)
        .then(response => response.json())
        .then(data => {
          console.log(data)
          this.MatchData = data.result
          this.formatGrade = this.MatchData.grade.replace(/\s/g, '\n')
          this.formatContent = this.MatchData.content.replace(/\s/g, '\n').replace(/。/g, '。<br>&nbsp;&nbsp;&nbsp;&nbsp;')
          this.isMatchShow = true
        })
        .catch(error => console.error(error))
    },
    handleSelected (date) {
      console.log(date)
      this.startDate = dayjs(date).format('YYYY-MM-DD')
    },
    drawCircleProgress () {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      // 绘制背景圆环
      this.ctx.beginPath()
      this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2)
      this.ctx.strokeStyle = '#fff'
      this.ctx.lineWidth = 10
      this.ctx.stroke()

      // 绘制进度圆弧
      this.endAngle = this.startAngle + this.progress / 100 * Math.PI * 2
      this.ctx.beginPath()
      this.ctx.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle)
      this.ctx.strokeStyle = '#967adc'
      this.ctx.lineWidth = 10
      this.ctx.stroke()
    },
    startAnimation () {
      setInterval(() => {
        if (this.progress < parseInt(this.renderList[0].content)) {
          this.progress++
          this.drawCircleProgress()
        }
      }, 10)
    }
  }
}
</script>

<style scoped lang="less">
.constellation-container {
  ::v-deep .van-nav-bar {
    color: #fff;
    height: 160px;
    background-color: #ac92eb;

    &:after {
      content: '';
      background: url("@/assets/downSelect.png") no-repeat;
      background-size: cover;
      height: 30px;
      width: 30px;
      position: absolute;
      top: 27px;
      left: 70%;
      z-index: 99;
    }
  }

  .todayDay {

    .selectedTime {
      text-align: center;
      background-color: transparent;
      position: fixed;
      color: #fff;
      top: 30px;
      border: none;
      left: 50%;
      transform: translateX(-50%);
      font-size: 18px;
      z-index: 2;
      font-family: "微软雅黑 Light", serif;

    }
  }

  .whiteWrap {
    width: 90%;
    height: 400px;
    background-color: #fff;
    z-index: 3;
    position: absolute;
    top: 85px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10px;

    .luckWrap {
      display: flex;
      justify-content: space-around;
      padding-top: 20px;

      .luckLeft {
        display: flex;
        flex-direction: column;
        align-items: center;

        ::v-deep .van-image {
          border: 3px solid #ac92eb;
        }

        .van-button {
          background-color: unset;
          border: none;
          font-size: 18px;
          color: #ac92eb;
          font-weight: bolder;
        }

        .time {
          font-size: 13px;
          color: #ac92eb;
        }
      }

      .luckRight {
        font-size: 12px;
      }
    }

    .circle-progress {
      position: absolute;
      top: 60%;
      left: 65%;
      display: inline-block;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;

      .progress-text {
        position: absolute;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background-color: #ac92eb;
        overflow: hidden;
      }

      .num {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        font-size: 22px;
        font-weight: bold;
      }

      .progress-canvas {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
      }
    }

    .sum {
      position: absolute;
      font-size: 14px;
      right: 48px;
      bottom: 30px;
    }

    .desc {
      margin-left: 20px;
      width: 50%;
      font-size: 12px;
      letter-spacing: 1px;
      opacity: .8;
    }
  }

  .doubleWrap {
    background-color: #fff;
    width: 90%;
    height: 120px;
    position: absolute;
    top: 500px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10px;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .van-button {
      border-radius: 10px;
      padding: 0px 30px;
      border: none;
    }

    .matchBtn {
      border-radius: 50%;
      box-shadow: 0 2px 10px 1px rgba(0, 0, 0, 0.2);

      &:active {
        transform: translateY(3px);
      }
    }

  }

  .van-dialog {
    font-size: 12px;
    padding: 0px 20px;
    width: 80%;

    ::v-deep .van-dialog__header {
      font-weight: bold;
      font-family: '微软雅黑', sans-serif;
      padding: 15px 0px;
      font-size: 16px;
    }

    .grade {
      text-align: center;
      margin-bottom: 6px;
      font-weight: bold;
    }

    .content {
      letter-spacing: 1px;
      opacity: .85;
      padding-bottom: 20px;
      text-indent: 2em;
      line-height: 18px;
    }
  }

  .progress-text:before,
  .progress-text:after {
    content: '';
    position: absolute;
    left: 50%;
    min-width: 90vw;
    min-height: 90vw;
    border-radius: 50%;
    background-color: #fff;
    animation: 2s rotate infinite linear;
  }

  ::v-deep .vc-title {
    font-size: 14px;
  }

  .progress-text:before {
    bottom: 20%;
    border-radius: 45%;
    -webkit-animation-duration: 10s;
    animation-duration: 10s;
  }

  .progress-text:after {
    bottom: 10%;
    opacity: 0.5;
    border-radius: 47%;
    animation-duration: 10s;
  }

  @-webkit-keyframes rotate {
    0% {
      transform: translate(-50%, 0) rotateZ(0deg);
    }
    50% {
      transform: translate(-50%, -2%) rotateZ(180deg);
    }
    100% {
      transform: translate(-50%, 0%) rotateZ(360deg);
    }
  }

  @keyframes rotate {
    0% {
      transform: translate(-50%, 0) rotateZ(0deg);
    }
    50% {
      transform: translate(-50%, -2%) rotateZ(180deg);
    }
    100% {
      transform: translate(-50%, 0%) rotateZ(360deg);
    }
  }
}
</style>
